import 'package:flutter/material.dart';
import '../models/airplane_model.dart';
import '../models/program.dart';
import '../models/program_block.dart';
import '../widgets/program_blocks_panel.dart';
import '../widgets/program_editor.dart';
import '../widgets/status_panel.dart';

/// 编程模式屏幕
class ProgrammingScreen extends StatefulWidget {
  final AirplaneModel airplaneModel;

  const ProgrammingScreen({super.key, required this.airplaneModel});

  @override
  State<ProgrammingScreen> createState() => _ProgrammingScreenState();
}

class _ProgrammingScreenState extends State<ProgrammingScreen> {
  // 当前程序
  late Program _program;
  // 是否正在执行程序
  bool _isRunning = false;
  // 执行状态信息
  String _executionStatus = '';

  @override
  void initState() {
    super.initState();
    _program = Program(name: '新程序');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('编程模式'),
        actions: [
          // 运行按钮
          Stack(
            alignment: Alignment.center,
            children: [
              if (_isRunning)
                const Padding(
                  padding: EdgeInsets.all(8.0),
                  child: SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  ),
                ),
              IconButton(
                icon: Icon(_isRunning ? Icons.stop : Icons.play_arrow),
                tooltip: _isRunning ? '停止' : '运行',
                onPressed: _toggleExecution,
              ),
            ],
          ),
          // 帮助按钮
          IconButton(
            icon: const Icon(Icons.help_outline),
            tooltip: '帮助',
            onPressed: _showHelpDialog,
          ),
        ],
      ),
      body: Column(
        children: [
          // 状态面板
          // Padding(
          //   padding: const EdgeInsets.all(8.0),
          //   child: StatusPanel(
          //     model: widget.airplaneModel,
          //     additionalInfo: _executionStatus.isNotEmpty
          //         ? {'执行状态': _executionStatus}
          //         : null,
          //   ),
          // ),

          // 主要内容区域
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // 程序块选择面板
                SizedBox(
                  width: 250,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ProgramBlocksPanel(),
                  ),
                ),

                // 分隔线
                const VerticalDivider(width: 1),

                // 程序编辑区域
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ProgramEditor(
                      program: _program,
                      onProgramChanged: (program) {
                        setState(() {
                          _program = program;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 底部状态栏
          Container(
            padding: const EdgeInsets.all(8.0),
            color: Colors.grey.shade200,
            child: Row(
              children: [
                Text('程序名称: ${_program.name}'),
                const Spacer(),
                Text('块数量: ${_countBlocks()}'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 切换程序执行状态
  void _toggleExecution() {
    if (_program.startBlocks.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('程序为空，无法执行')));
      return;
    }

    setState(() {
      _isRunning = !_isRunning;
      if (_isRunning) {
        _executionStatus = '程序开始执行';
        _executeProgram();
      } else {
        _executionStatus = '程序已停止';
      }
    });
  }

  // 执行程序
  Future<void> _executeProgram() async {
    if (!_isRunning) return;

    // 模拟程序执行
    for (var startBlock in _program.startBlocks) {
      if (!_isRunning) break;
      await _executeBlock(startBlock);
    }

    // 执行完成后自动停止
    if (_isRunning) {
      setState(() {
        _isRunning = false;
        _executionStatus = '程序执行完成';
      });
    }
  }

  // 执行单个程序块
  Future<void> _executeBlock(ProgramBlock block) async {
    if (!_isRunning) return;

    // 更新执行状态
    setState(() {
      _executionStatus = '正在执行: ${block.name}';
    });

    // 根据块类型执行不同操作
    switch (block.type) {
      case BlockType.motion:
        // 模拟运动操作
        await Future.delayed(const Duration(seconds: 1));
        break;
      case BlockType.control:
        // 执行控制块
        if (block.name == '等待') {
          final seconds = block.parameterValues['秒数'] ?? 1.0;
          await Future.delayed(
            Duration(milliseconds: (seconds * 1000).toInt()),
          );
        } else if (block.name == '重复') {
          final times = block.parameterValues['次数']?.toInt() ?? 1;
          for (var i = 0; i < times; i++) {
            if (!_isRunning) break;
            for (var child in block.children) {
              if (!_isRunning) break;
              await _executeBlock(child);
            }
          }
        }
        break;
      case BlockType.event:
        // 事件块通常是起始块，不需要特殊处理
        break;
      case BlockType.operator:
        // 运算块通常作为参数，不需要单独执行
        break;
      case BlockType.sensor:
        // 传感器块通常作为参数，不需要单独执行
        break;
    }

    // 执行下一个块
    if (block.next != null) {
      await _executeBlock(block.next!);
    }
  }

  // 计算程序中的块数量
  int _countBlocks() {
    int count = 0;

    void countBlock(ProgramBlock? block) {
      if (block == null) return;
      count++;
      for (var child in block.children) {
        countBlock(child);
      }
      countBlock(block.next);
    }

    for (var startBlock in _program.startBlocks) {
      countBlock(startBlock);
    }

    return count;
  }

  // 显示帮助对话框
  void _showHelpDialog() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('编程模式帮助'),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: const [
                  Text(
                    '编程模式使用说明:',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Text('1. 从左侧面板选择程序块，拖放到右侧编辑区域'),
                  Text('2. 事件块（黄色）用于开始程序'),
                  Text('3. 运动块（蓝色）用于控制飞机移动'),
                  Text('4. 控制块（橙色）用于循环和条件判断'),
                  Text('5. 运算块（绿色）用于数学计算'),
                  Text('6. 传感器块（紫色）用于获取飞机状态'),
                  SizedBox(height: 16),
                  Text('提示:', style: TextStyle(fontWeight: FontWeight.bold)),
                  SizedBox(height: 8),
                  Text('- 点击程序块可以编辑其参数'),
                  Text('- 点击运行按钮执行程序'),
                  Text('- 程序执行时可以随时点击停止按钮'),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
    );
  }
}
